import sharp from "sharp"
import sizeOf from "image-size"
import { resolve } from 'node:path'
import { JOURNAL_IMG_FOLDER } from "../../config"

/**
 * 
 * @param filename 文件名，如：xxx.jpg
 * @param dirpath 文件路径，存储路径，如：/public/journal-img
 * @returns 
 */
export async function cutJournalImgHelper(filename: string, dirpath: string) {
  const minFilename = `min-${filename}`
  const filepath = resolve(dirpath, filename)
  const outpath = resolve(dirpath, minFilename)
  const { width, height } = sizeOf(filepath)
  const newWidth = width > 200 ? 200 : width
  const newHeight = Math.floor(height * (newWidth / width))

  try {
    const result = await sharp(filepath)
      .resize(newWidth, newHeight)
      // .toBuffer()
      .toFile(outpath)
    if (result) {
      return {
        code: 200,
        message: `/${JOURNAL_IMG_FOLDER}/${minFilename}`
      }
    }

  } catch (err) {
    return {
      code: 500,
      message: "裁剪失败"
    }
  }

}